# -*- coding: utf-8 -*-
import baostock as bs
import pandas as pd
import datetime

if __name__ == '__main__':
    # 登陆系统
    lg = bs.login()
    # 显示登陆返回信息
    print('login respond error_code:'+lg.error_code)
    print('login respond  error_msg:'+lg.error_msg)
     
    now  = datetime.datetime.now()
    today = now.strftime('%Y-%m-%d')
    today_7 = (now + datetime.timedelta(days=-30)).strftime('%Y-%m-%d')
    print(today)
    print(today_7)

    rs = bs.query_history_k_data_plus("sh.000922",
    "date,code,open,high,low,close,preclose,volume,amount,pctChg",
    start_date=today_7, end_date=today, frequency="d")

    print('query_history_k_data_plus respond error_code:'+rs.error_code)
    print('query_history_k_data_plus respond  error_msg:'+rs.error_msg)

    # 打印结果集
    data_list = []
    while (rs.error_code == '0') & rs.next():
        # 获取一条记录，将记录合并在一起
        data_list.append(rs.get_row_data())
    result = pd.DataFrame(data_list, columns=rs.fields)
    # 结果集输出到csv文件
    result.to_csv("D:\\history_Index_k_data.csv", index=False)
    print(result)

    # 登出系统
    bs.logout()